<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

<!--      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>-->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['retirement:retirementCarousel:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['retirement:retirementCarousel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['retirement:retirementCarousel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['retirement:retirementCarousel:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="retirementCarouselList" >
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="绑定文章" align="center" prop="titName" />
      <el-table-column label="轮播图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['retirement:retirementCarousel:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['retirement:retirementCarousel:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改轮播图配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="绑定文章" prop="articleId">
          <el-select
            clearable
            v-model="form.articleId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入标题"
            :remote-method="searchArticle"
            :loading="articleLoading"
            @change="handleArticleChange"
          >
            <el-option
              v-for="item in articleList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
              <span style="float: left">{{ item.title }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="轮播图片" prop="image">
          <image-upload v-model="form.image" :limit="1"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRetirementCarousel, getRetirementCarousel, delRetirementCarousel, addRetirementCarousel, updateRetirementCarousel } from "@/api/retirement/retirementCarousel"
import { getListRetirementArticle } from "@/api/retirement/retirementArticle"

export default {
  name: "RetirementCarousel",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 轮播图配置表格数据
      retirementCarouselList: [],
      // 文章列表数据
      articleList: [],
      // 文章加载状态
      articleLoading: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        articleOneClass: null,
        articleTwoClass: null,
        articleId: null,
        image: null,
        content: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        articleId: [
          { required: true, message: "绑定文章不能为空", trigger: "change" }
        ],
        image: [
          { required: true, message: "轮播图片不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getArticleList()
  },
  methods: {
    /** 查询轮播图配置列表 */
    getList() {
      this.loading = true
      listRetirementCarousel(this.queryParams).then(response => {
        this.retirementCarouselList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询文章列表 */
    getArticleList() {
      const params = {
        status: '3'
      }
      getListRetirementArticle(params).then(response => {
        this.articleList = response.rows || response.data || []
      })
    },
    /** 搜索文章 */
    searchArticle(query) {
      this.articleLoading = true
      if (!query)  this.getArticleList()
      const params = {
        status: '3',
        title: query
      }
      // 有搜索关键词时，根据标题搜索
      getListRetirementArticle(params).then(response => {
        this.articleList =  response.data || []
        this.articleLoading = false
      })
    },
    /** 文章选择变化处理 */
    handleArticleChange(articleId) {
      if (articleId) {
        // 查找选中的文章信息
        const selectedArticle = this.articleList.find(item => item.id === articleId)
        if (selectedArticle) {
          // 打印选中文章的信息
          console.log('选中的文章信息:', selectedArticle)
          // 如果文章有image字段，自动回填到轮播图片
          if (selectedArticle.image) {
            this.form.articleType = selectedArticle.type
            this.form.image = selectedArticle.image
            this.$message.success('默认回填文章封面图,可自行修改')
          } else {
            this.$message.warning('该文章没有图片，请自行上传轮播图片')
          }
        }
      } else {
        // 清空选择时，也清空轮播图片
        this.form.image = null
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        articleOneClass: null,
        articleTwoClass: null,
        articleId: null,
        articleType: null,
        image: null,
        content: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加轮播图配置"
      // 确保有文章数据可供选择
      if (this.articleList.length === 0) {
        this.getArticleList()
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getRetirementCarousel(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改轮播图配置"
        // 确保有文章数据可供选择
        if (this.articleList.length === 0) {
          this.getArticleList()
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRetirementCarousel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addRetirementCarousel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除轮播图配置编号为"' + ids + '"的数据项？').then(function() {
        return delRetirementCarousel(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    }
  }
}
</script>
